//
//  comInfoViewController.swift
//  NewLndd
//
//  Created by 邵禹曦 on 2020/1/7.
//  Copyright © 2020 辽宁当代. All rights reserved.
//

import UIKit
import SwiftyJSON


// MARK: - 商品信息
class comInfoViewController: HomeApiViewController,UIPickerViewDelegate,UIPickerViewDataSource {
   


    
    // 定义数组  Use of undeclared type 'Status'  数组 : [模型Model]
    private lazy var ViewModels : [comInfo] = [comInfo]()
    var _comInfo = putUpView()
    @IBOutlet weak var pickerView: UIPickerView!
    
    // 获取下拉coi
    var _coi : String = ""
    // 下拉的数据
    var coi : [String] = []
    
    
    // 产品代码
    @IBOutlet weak var psdm: UITextField!
    // 产品名称
    @IBOutlet weak var cpmc: UILabel!
    // 昨结价
    @IBOutlet weak var zjj: UILabel!
    // 交易单位 CTS
    @IBOutlet weak var CTS: UILabel!
    // 单笔最大挂单数量OMOQ
    @IBOutlet weak var OMOQ: UILabel!
    //最小变动价MPM
    @IBOutlet weak var MPM: UILabel!
    //最小变动数量MQM
    @IBOutlet weak var MQM: UILabel!
    //是否开启标码提货IL
    @IBOutlet weak var IL: UILabel!
    //交收交易单位换算CQ
    @IBOutlet weak var CQ: UILabel!
    //产品状态CS
    @IBOutlet weak var CS: UILabel!
    //当日涨幅上限SPU
    @IBOutlet weak var SPU: UILabel!
    //最后交易日LTD
    @IBOutlet weak var LTD: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        showInfo()
        
    }
    
}


extension comInfoViewController {
    private func showInfo() {
        
        //self.pickerView.isHidden = true
        //self.pickerView.removeFromSuperview()
           // GCD
           let group = DispatchGroup()
    
           // 从沙盒中获取参数
            var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
            userPath =  (userPath as NSString).appendingPathComponent("data.plist")
            user = NSKeyedUnarchiver.unarchiveObject(withFile: userPath) as? User
        
        // 先睡0.4
        //perform(#selector(scrollViewDidEndDecelerating), with: self, afterDelay: 0.4)
        Thread.sleep(forTimeInterval: 0.05)


           // 用户验证
           self.u = user?.U!
           self.retcode = user?.RETCODE!
           // 用户验证
           let str = [u,"101",retcode]
            
           //self.isLogin = self._network(str: str as! [String], group: group)
        group.enter()
        NetworkTools.share.check_user(code: str as Array<Any>) { (result, error) in
                      
                          if error != nil {
                              print("no no no")
                              return
                          }
                          

                          if Int(self._retcode(res: result!))! < 0 {
                              self.isLogin = false
                          } else {
                              self.isLogin = true
                          }
                          group.leave()
                      }

           group.notify(queue: DispatchQueue.main) {
               if !self.isLogin {
                   return self.setupVisitorView()
               } else {
                Thread.sleep(forTimeInterval: 0.05)
                // 1.获取第一条数据
                self.ShouInfo()
                // 1.1获取下拉框内容
                self.tableShouInfo()
                // 2.点击给下拉框
                // 3.选择下拉框后替换数据
                
                
                
                
                
                    
                    //self.setupNavigationBar()
                    
                    //self.goInfo()
                    
               }
            }
       }
}

// MARK: - 设置UI界面
extension comInfoViewController {
    
    private func setupNavigationBar() {
        //psdm.addTarget(self, action: #selector(selectDate(_:)), for: .touchDown)
    
    }
    
    @objc func selectDate(_ btn: UITextField) {
        //print(self.psdm.text)
        self.performSegue(withIdentifier: "cpxl", sender: self.psdm.text)
        //self.pickerView.isHidden = false
        
        //self.pickerView.removeFromSuperview()

    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // 买挂单
        if segue.identifier == "cpxl" {
            let secVC = segue.destination as! comInfoPickerViewController
            //if let IndexPath = sender as? putUpView {
            secVC._comInfo?.COI = sender as? String
            //}
        }
        
     
    }
}


// MARK: - 优化用
extension comInfoViewController {
    private func goInfo() {
        //coiBtn.addTarget(self, action: #selector(BtnClick), for: .touchUpInside)
    }
    
    @objc private func BtnClick()  {
        print("111")
        //self.pickerView.isHidden = false
        //self.pickerView.removeFromSuperview()
    }
    
    // 列数
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    // 行数
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 3
        
    }
    
    // 返回具体值
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return "aaa"
    }
    
    // 点击
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        //self.pickerView.isHidden = true
        //NSLog(self.coi[row])
    }
    
    // 行高
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 35.0
    }
        
}



extension comInfoViewController {
    // MARK: - TableViewShowInfo
    @objc private func tableShouInfo() {
        // GCD
        let group = DispatchGroup()
        // 获取下拉数据
        let str = [user?.U!,user?.RETCODE! , "", ""]
        group.enter()
        NetworkTools.share.commodity_query(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            
            //print(resultArray)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) < 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "数据加载失败")
                            return self.setupVisitorView()
                        }
                    }
                }
            }
            
            
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let resultList = REP["RESULTLIST"] as? [String : AnyObject] {
                    for temp in resultList["REC"] as! NSArray {
                        let sta = comInfo(dict: temp as! [String : AnyObject])
                        self.coi.append(sta.COI!)
                        //self.ViewModels.append(sta)
                        
                    }
                    
                    //print(self.coi.count)
                }
            }
      group.leave()
        }
        
        
        group.notify(queue: DispatchQueue.main) {
            self.psdm.addTarget(self, action: #selector(self.selectDate(_:)), for: .touchDown)
            
        }
    }
    
    
    
    
    
    
    
    // 显示数据默认第一条
    @objc private func ShouInfo() {
        let str = [user?.U!,user?.RETCODE! , _coi, ""]
        NetworkTools.share.commodity_query(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            
            //print(resultArray)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) < 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "数据加载失败")
                            return self.setupVisitorView()
                        }
                    }
                }
            }
            
            let rstJson = JSON(resultArray)
            // 如果初始化数据

            self.psdm.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["COI"].stringValue )
            self.cpmc.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["CON"].stringValue )
            self.zjj.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["PRC"].stringValue )
            // 交易单位 CTS
            self.CTS.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["CTS"].stringValue )
            // 单笔最大挂单数量OMOQ
            self.OMOQ.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["OMOQ"].stringValue )
            //最小变动价MPM
            self.MPM.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["MPM"].stringValue )
            //最小变动数量MQM
            self.MQM.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["MQM"].stringValue )
            //是否开启标码提货IL
            self.IL.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["IL"].stringValue )
            //交收交易单位换算CQ
            self.CQ.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["CQ"].stringValue )
            //产品状态CS
            self.CS.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["CS"].stringValue )
            //当日涨幅上限SPU
            self.SPU.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["SPU"].stringValue )
            //最后交易日LTD
            self.LTD.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["LTD"].stringValue )
        }
            
    }
    
    
    
}
